<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * @author Xubi Nguyen
 * @copyright 2011
 */
 
include(BASEPATH.'core/Template'.EXT);

class CI_Admin extends CI_Template
{
   var $config;
   var $time_exit=0;
   var $CI;
   var $action;
   var $login;
   
   
   function __construct()
   {
   		parent::__construct('backend');
   		$this->CI->load->model(array('config_model','login_model'));

   		
   		$config=array('serversms','session_name','session_length','look_count','look_length','tmpl_admin','numrows','copyright','page_option','sitename','timeinsert','timeedit','timeend','ngaycanhbao','ngayquantriet','email','smsserver','linksoap','thongbao','lienhe','linksoapphu');

   		$this->config=$this->CI->config_model->get($config);
   		$this->time_exit=($this->config['session_length']*60);
        $this->set_master_template();
        
		$this->CI->login_model->DeleteAll($this->time_exit);  
		$sid = $this->GetSession('login'); 
        

        $this->login = $this->CI->login_model->get($sid);
        $class = $this->CI->router->class;
     
		if($class!='sms'){
			if($class!='home' && $class!='authorize')
				$this->SetSession('current_controll',$class);

                $method = $this->CI->router->method;
               
    			if(!is_array($this->login))
                { 
                    
                    
                    if($class == 'authorize')
                    {
                        
                        if($method == 'changepass' || $method == 'savepass')
                        {
                            $login_temp = $this->GetSession('login_temp');
                            if(empty($login_temp))
                                redirect(admin_url());
                        }
                        else if($method != 'login' && $method != 'logout'  && $method != 'index'  && $method != 'captcha') 
                        {
                            redirect(admin_url());
                        }
                    }
                    
                    if($class == 'home') 
                    {
                        redirect(admin_url());
                    }
                    if($class!='authorize')
                    {
                        if($method == 'thongke' || $method == 'export')
                        {
                            echo '<script>parent.window.parent.window.location="'.admin_url().'"</script>';
                        }
                        else
                        {
                            echo '<script>parent.window.location="'.admin_url().'"</script>';
                        }
                        exit();
                    }
                   
                }
            
            if(is_array($this->login) && $class == 'authorize' && $method != 'logout')  redirect(admin_url().'home'.url_suffix());
		 
			$this->action = $this->GetAction();
			if(!$this->action && $class!='authorize' && $class!='home'  && $class!='welcome') 
				show_404();      
			
	
			$this->CI->login_model->SetTime($sid);
			
			
			$this->add_region('copyright');
			
			$this->write('copyright',$this->config['copyright'],true);
			$this->write('title_page',$this->config['sitename'],true);
		}
   }  
   
   function resetPage($s)
   {
   		$action = $this->CI->uri->segment($s);
		$s_action = $this->GetSession('action');
		if($action=='' || $action!=$s_action)
		{
			$this->SetSession('action',$action);
			$this->SetSession('page',0);
		}
   }
   
   /**
	 * Run the master template or a single region
	 *
	 * @access	public
     * @param	string	the name of the "view" file to be included.
	 * @param	string	optionally opt to render a specific region
	 * @param	boolean	FALSE to output the rendered template, TRUE to return as a string. Always TRUE when $region is supplied
	 * @return	void or string (result of template build)
	 */
   
   function run($file, $data = NULL, $region = NULL, $buffer = FALSE, $parse = FALSE)
   {
      $content=$this->CI->load->view($file,$data,true);
	  $this->write('content',$content);
      $this->render($region, $buffer, $parse);
   }
   
   public function check_uploadfiles($file_name='')
	{
		//them kiem tra duoi file import
		$allowed_types = array(
		
		/* document extensions */                               
		'xls', 'xlsx'
								);
		
		
		$mime_type_black_list= array(
		# HTML may contain cookie-stealing JavaScript and web bugs
		'text/html', 'text/javascript', 'text/x-javascript',  'application/x-shellscript',
		# PHP scripts may execute arbitrary code on the server
		'application/x-php', 'text/x-php', 'text/x-php',
		# Other types that may be interpreted by some servers
		'text/x-python', 'text/x-perl', 'text/x-bash', 'text/x-sh', 'text/x-csh',
		'text/x-c++', 'text/x-c',
		# Windows metafile, client-side vulnerability on some systems
		# 'application/x-msmetafile',
		# A ZIP file may be a valid Java archive containing an applet which exploits the
		# same-origin policy to steal cookies      
		# 'application/zip',
								);
		
		
		$tmp_file_extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
//		print_r(end(explode('.', $file_name)).'---'. $allowed_types);exit;
		
		if(!in_array(end(explode('.', $file_name)), $allowed_types))
		{
				return 'Invalid file type';
				exit(0);
		}
		elseif(in_array(end(explode('.', $file_name)), $mime_type_black_list))
		{
				return 'Invalid file type';
				exit(0);
		}
		else return 1;
		
		if(!strlen($tmp_file_extension) || (
		  !in_array($tmp_file_extension,$allowed_types))) {
			return 0;
		}
		
	
	}
   public function Captcha($width=100, $height=30, $length=6){
		$chars = '0123456789';//abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXY'; // O  and 0 (Zero) are visually similar, that's why I am not using it
		$RandomStr = '';
		
		for($i = 0; $i < $length; $i++){ // Generating the captcha string

		   $pos = mt_rand(0, strlen($chars)-1);

		   $RandomStr .= substr($chars, $pos, 1);

		}

		$ResultStr = $RandomStr;
		
		$NewImage =imagecreatefromjpeg(FCPATH.'/captcha/img.jpg');//image create by existing image and as back ground 
		
		$TextColor = imagecolorallocate($NewImage, 0, 0, 0);//text color-Black
		
		$line_clr = imagecolorallocate($NewImage, 0, 255, 11);
		//Top left to Bottom Left	
		imageline($NewImage, 0, $height-22, $width, $height-1, $line_clr);	
		// Bottom Left to Bottom Right	
		imageline($NewImage, $width-1, 0, $width-100, $height, $line_clr);
		imageline($NewImage, $height-1, 0, $width-100, $width, $line_clr);
		imageline($NewImage, $width-1, 0, $height-1, $width, $line_clr);
		
			
		imagestring($NewImage,5, 20, 6, $ResultStr, $TextColor);// Draw a random string horizontally 
		
		
		$this->SetSession('captcha_val', md5($ResultStr));// carry the data through session
		
		
		header("Content-type: image/jpeg");// out out the image 
		
		imagejpeg($NewImage);//Output image to browser 
		
	}

	public function Ran($length = 6, $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXY'){
        $RandomStr = '';

        for($i = 0; $i < $length; $i++){

           $pos = mt_rand(0, strlen($chars)-1);

           $RandomStr .= substr($chars, $pos, 1);

        }
        return $RandomStr;
    }
	public function Get_trungtam($bientruyen='',$laytt='',$laytieude='',$mottrungtam='')
	 {
		 //bientruyen=id ma array la lay id
		 //bientruyen='ma' ma  array la lay  ma
		 //laytt: laytt = 2 la lay trung tam ,
		 //khac 1 lay tieu de
		$sql_dv="SELECT `id`,ma, `ten` FROM (`trungtam`) where thungracgiaoban=0";
		if($laytt==2)
			$sql_dv.=" and loai = 2";
		if($laytt==1)
			$sql_dv.=" and loai = 1";
		if($mottrungtam!='')
		{
			if($bientruyen=='id')
				$sql_dv.=" and id = ".$mottrungtam."";
			if($bientruyen=='ma')
				$sql_dv.=" and ma = '".$mottrungtam."'";
			
		}
		$sql_dv.=" order by id";	
		
		$combo_donvis=$this->ketnoi_sql($sql_dv,'get');// print_r($sql_dv);exit;
		if($laytieude!=1)
			$combo_donvi['']="Đơn vị...";
		if(count($combo_donvis))
			if($bientruyen=='id')
				foreach($combo_donvis as $dv)
				{
					$combo_donvi[$dv["id"]]=$dv["ten"];
				}
			else
				foreach($combo_donvis as $dv)
				{
					
					$combo_donvi[$dv["ma"]]=$dv["ten"];
				}	
		return $combo_donvi;
	 } 
	 public function Get_trungtam_kothunracgiaoban($bientruyen='',$laytt='',$laytieude='',$mottrungtam='')
	 {
		 //bientruyen=id ma array la lay id
		 //bientruyen='ma' ma  array la lay  ma
		 //laytt: laytt = 2 la lay trung tam ,
		 //khac 1 lay tieu de
		$sql_dv="SELECT `id`,ma, `ten` FROM (`trungtam`) where 1=1";
		if($laytt==2)
			$sql_dv.=" and loai = 2";
		if($laytt==1)
			$sql_dv.=" and loai = 1";
		if($mottrungtam!='')
		{
			if($bientruyen=='id')
				$sql_dv.=" and id = ".$mottrungtam."";
			if($bientruyen=='ma')
				$sql_dv.=" and ma = '".$mottrungtam."'";
			
		}
		$sql_dv.=" order by id";	
		
		$combo_donvis=$this->ketnoi_sql($sql_dv,'get');// print_r($sql_dv);exit;
		if($laytieude!=1)
			$combo_donvi['']="Đơn vị...";
		if(count($combo_donvis))
			if($bientruyen=='id')
				foreach($combo_donvis as $dv)
				{
					$combo_donvi[$dv["id"]]=$dv["ten"];
				}
			else
				foreach($combo_donvis as $dv)
				{
					
					$combo_donvi[$dv["ma"]]=$dv["ten"];
				}	
		return $combo_donvi;
	 } 
	public function ketnoi_sql($sql='',$kieuthucthi=''){
		//thuc hien webservice
		$link = $this->config['linksoap'];
		//$this->load->helper('nusoap');
		$this->CI->load->helper('nusoap');
		//$sql="SELECT `id`, `ten` FROM (`trungtam`) WHERE `thungrac` = 0";
		$param = array('sql' => $sql, 'db' => 'quanlyuser');
		$client = new nusoap_client($link);
		//////////////////////////////////
		$client->setCredentials("viettel", "viettel@1234", "basic");

		/////////////////////////////////
		$client->soap_defencoding = 'UTF-8';
		$client->decode_utf8 = false;
		if($kieuthucthi=='get'){
			$response = $client->call('getdata', $param);
			if($client->fault){
				$linkphu = $this->config['linksoapphu'];
				$clients = new nusoap_client($linkphu);
				//////////////////////////////////
				$clients->setCredentials("viettel", "viettel@1234", "basic");
		
				/////////////////////////////////
				$clients->soap_defencoding = 'UTF-8';
				$clients->decode_utf8 = false;
				$responsephu = $clients->call('getdata', $param);
				if($clients->fault){
					return "FAULT: <p>Code: (".$clients->faultcode.")</p>String: ".$clients->faultstring;
				}
				else
					return $responsephu;
			}
			else{
				return $response;
			}
		}
		else{	//print_r($sql);exit;
			$response = $client->call('sqlexecute', $param);
		//=============S upadte du lieu vao them database du phong=====================
			$linkphu = $this->config['linksoapphu'];
			$clients = new nusoap_client($linkphu);
			$clients->soap_defencoding = 'UTF-8';
			$clients->decode_utf8 = false;
			$responsephu = $clients->call('sqlexecute', $param);
       //=============E upadte du lieu vao them database du phong=====================
			if($client->fault){
				return "FAULT: <p>Code: (".$client->faultcode.")</p>String: ".$client->faultstring;
			}
			else
			{
				return $response;
			}
	//		print_r($param['sql']);exit;
		}
	}    
		
  function CreateCookie($admin_cookie_name, $admin_cookie_data, $admin_cookie_time, $type='d')
   {
        switch($type)
        {
            case 's':
                $time = $admin_cookie_time;
                break;
            case 'm':
                $time = $admin_cookie_time*60;
                break;
            case 'h':
                $time = $admin_cookie_time*3600;
                break;
            case 'd':
                $time = $admin_cookie_time*86400;
                break;
            case 'w':
                $time = $admin_cookie_time*86400*7;
                break;
            case 'M':
                $time = $admin_cookie_time*2678400;
                break;
            default:
                $time = $admin_cookie_time*32140800;    
        }
        
        $domain = $this->CI->config->item('admin_cookie_domain');
        $path = $this->CI->config->item('admin_cookie_path');
        setcookie('admin_cookie_'.$admin_cookie_name.'_'.$this->config['session_name'], $admin_cookie_data, time()+$time, $path, $domain, 0);
   }
   
   function SetCookie($admin_cookie_name, $admin_cookie_data)
   {
   		$_COOKIE['admin_cookie_'.$admin_cookie_name.'_'.$this->config['session_name']] = $admin_cookie_data;
   }
   
   function NameCookie($admin_cookie_name)
   {
	 return 'admin_cookie_'.$admin_cookie_name.'_'.$this->config['session_name'];
   }
   
   function GetCookie($admin_cookie_name)
   {
		return (isset($_COOKIE['admin_cookie_'.$admin_cookie_name.'_'.$this->config['session_name']])?$_COOKIE['admin_cookie_'.$admin_cookie_name.'_'.$this->config['session_name']]:"");
   }
   
   function DeleteCookie($admin_cookie_name)
   {   	
		 $domain = $this->CI->config->item('admin_cookie_domain');
        $path = $this->CI->config->item('admin_cookie_path');
        setcookie('admin_cookie_'.$admin_cookie_name.'_'.$this->config['session_name'], '', 0, $path, $domain, 0);
   }
   
   function SetSession($name,$value)
	{
		$this->CI->session->set_userdata('admin_'.$name.'_'.$this->config['session_name'],$value);
	}
    
     function SetFlashData($name,$value)
	{
		$this->CI->session->set_flashdata('admin_'.$name.'_'.$this->config['session_name'],$value);
	}
	
	function GetFlashData($name)
	{
		return $this->CI->session->flashdata('admin_'.$name.'_'.$this->config['session_name']);
	}
	
	function GetSession($name)
	{
		return $this->CI->session->userdata('admin_'.$name.'_'.$this->config['session_name']);
	}
	
	function DeleteSession($name)
	{
		return $this->CI->session->unset_userdata('admin_'.$name.'_'.$this->config['session_name']);
	}
	
        
   function BoDau($str)
	{
	    $str = preg_replace("/(à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ)/", 'a', $str);
		$str = preg_replace("/(è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ)/", 'e', $str);
		$str = preg_replace("/(ì|í|ị|ỉ|ĩ)/", 'i', $str);
		$str = preg_replace("/(ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ)/", 'o', $str);
		$str = preg_replace("/(ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ)/", 'u', $str);
		$str = preg_replace("/(ỳ|ý|ỵ|ỷ|ỹ)/", 'y', $str);
		$str = preg_replace("/(đ)/", 'd', $str);
		$str = preg_replace("/(À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ)/", 'A', $str);
		$str = preg_replace("/(È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ)/", 'E', $str);
		$str = preg_replace("/(Ì|Í|Ị|Ỉ|Ĩ)/", 'I', $str);
		$str = preg_replace("/(Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ)/", 'O', $str);
		$str = preg_replace("/(Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ)/", 'U', $str);
		$str = preg_replace("/(Ỳ|Ý|Ỵ|Ỷ|Ỹ)/", 'Y', $str);
		$str = preg_replace("/(Đ)/", 'D', $str);
		$str = preg_replace("/( |'|,|\||\.|\"|\?|\/|\%|–|!)/", '-', $str);
		$str = preg_replace("/(\()/", '-', $str);
		$str = preg_replace("/(\))/", '-', $str);
		$str = preg_replace("/(&)/", '-', $str);
		return strtolower($str);
	}
	
    function BoDau2($str)
	{
	    $str = preg_replace("/(à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ)/", 'a', $str);
		$str = preg_replace("/(è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ)/", 'e', $str);
		$str = preg_replace("/(ì|í|ị|ỉ|ĩ)/", 'i', $str);
		$str = preg_replace("/(ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ)/", 'o', $str);
		$str = preg_replace("/(ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ)/", 'u', $str);
		$str = preg_replace("/(ỳ|ý|ỵ|ỷ|ỹ)/", 'y', $str);
		$str = preg_replace("/(đ)/", 'd', $str);
		$str = preg_replace("/(À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ)/", 'A', $str);
		$str = preg_replace("/(È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ)/", 'E', $str);
		$str = preg_replace("/(Ì|Í|Ị|Ỉ|Ĩ)/", 'I', $str);
		$str = preg_replace("/(Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ)/", 'O', $str);
		$str = preg_replace("/(Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ)/", 'U', $str);
		$str = preg_replace("/(Ỳ|Ý|Ỵ|Ỷ|Ỹ)/", 'Y', $str);
		$str = preg_replace("/(Đ)/", 'D', $str);
		return $str;
	}
    
    function BoDau3($str)
	{
	    $str = preg_replace("/(à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ)/", 'a', $str);
		$str = preg_replace("/(è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ)/", 'e', $str);
		$str = preg_replace("/(ì|í|ị|ỉ|ĩ)/", 'i', $str);
		$str = preg_replace("/(ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ)/", 'o', $str);
		$str = preg_replace("/(ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ)/", 'u', $str);
		$str = preg_replace("/(ỳ|ý|ỵ|ỷ|ỹ)/", 'y', $str);
		$str = preg_replace("/(đ)/", 'd', $str);
		$str = preg_replace("/(À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ)/", 'A', $str);
		$str = preg_replace("/(È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ)/", 'E', $str);
		$str = preg_replace("/(Ì|Í|Ị|Ỉ|Ĩ)/", 'I', $str);
		$str = preg_replace("/(Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ)/", 'O', $str);
		$str = preg_replace("/(Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ)/", 'U', $str);
		$str = preg_replace("/(Ỳ|Ý|Ỵ|Ỷ|Ỹ)/", 'Y', $str);
		$str = preg_replace("/(Đ)/", 'D', $str);
        $str = preg_replace("/( |'|,|\||\"|\?|\/|\%|–|!)/", '_', $str);
       // $str =  str_replace(" ", '_', $str);
		return strtolower($str);
	}
    
    function checkTableExist($table)
	{
		if($this->CI->db->table_exists($table)){
			return true;
		}
		else{
			return false;	
		}
	}        
    function createTable($name,$fields)
    {
        $this->CI->load->dbforge();

        $this->CI->dbforge->add_field($fields);
        
        $this->CI->dbforge->create_table($name);
    }
    
    function GetAction()
    {
        $controller = $this->CI->router->class;
        $this->CI->db->select('id');
        $this->CI->db->where('link',$controller);
        $this->CI->db->where('title <>','sep');
		$table=$this->CI->db->get('menus');
        if($table->num_rows()>0)
        {
            $data = $table->row_array();
            $menu = $this->getMenuUser();
            return (isset($menu[$data['id']])?$menu[$data['id']]:false);           
        }
        return false;
    }
    
    function getMenuUser()
    {
        //$user = $this->GetSession('login');
        $menuuser = $this->getGroups();
        $this->CI->db->select('params');
		$this->CI->db->where_in('id',$menuuser);
		$table=$this->CI->db->get('groups');
        $amenus = array();
      
        $n  = $table->num_rows();
        if($n>0)      
        {
            for($i=0; $i<$n; $i++)
            {
               $temp = $table->row_array($i);
                $menus = json_decode($temp['params'],true);
                foreach($menus as $k=>$v)
                {
                   if(!isset($amenus[$k]))
                    $amenus[$k] = $v;
                }
                    
           }
        }  
        return $amenus;
    }
    
    function getGroups()
    {
       	//$sql="SELECT `groups` FROM (`nhanvien`) WHERE `id` = '".$this->login['id']."'";
		if($this->login['taikhoan']=='admin')
			$sql="SELECT `groups` FROM (`user_pm_groups`) WHERE `taikhoan` = '".$this->login['taikhoan']."'";
		else
			$sql="SELECT `groups` FROM (`user_pm_groups`) WHERE `taikhoan` = '".$this->login['taikhoan']."'  AND `phanmem` LIKE '".$this->config['session_name']."'";
		$tables=$this->ketnoi_sql($sql,'get');
		$table=$tables[0];
	  /*  $this->CI->db->select('groups');
		$this->CI->db->where('id',$this->login['id']);
		$table = $this->CI->db->get('users');
        $table = $table->row_array();*/
        return explode(',',$table['groups']);
    }
        
	function phantrang($count,$rows,$links,$task,$page=0)
	{
		$CI =& get_instance();
		$config['base_url'] = base_url().'/admin/'.$task;
		$config['total_rows'] =$count; 
		$config['per_page'] = $rows;
		$config['num_links'] = $links;
		
		$num_pages = (!empty($rows))?ceil($count /$rows):1;		
		$cur_page = $page;
		$cur_page = (int) $cur_page;
	
		if ( ! is_numeric($cur_page))
		{
			$cur_page = 0;
		}

		if ($cur_page > $count)
		{
			$cur_page = ($num_pages - 1) * $rows;
		}
		
		$cur_page = floor(($cur_page/$rows) + 1);
	
		$config['full_tag_open'] = '<div class="pagination">';
		$config['full_tag_close'] = '<div class="limit">Trang thứ '.$cur_page.' / '.ceil($count/$rows).'</div></div>';
				
		$config['first_link'] = '&nbsp;';
		$config['prev_link'] = '&nbsp;';
		$config['next_link'] = '&nbsp;';
		$config['last_link'] = '&nbsp;';
		$CI->load->library('pagination');
		$CI->pagination->initialize($config);
		return $CI->pagination->create_links($page);
	}
	
	//================================================
	

}

function pageOption()
{
	$admin= new CI_Admin();
	
    $cur = $admin->config['numrows'];
    $op = $admin->config['page_option'];
    $op = explode(',',$op);
    $str = '';
    foreach($op as $item)
    {
        $str.='<option ';
        if($item==$cur)
            $str.='selected="selected" ';
       $str.='value="'.$item.'">'.$item.'</option>';
    }
    return $str;
}

function admin_url()
{
	$m = SELF;
    $m = explode('.',$m);
    $m = $m[0];
    $m = ($m=='index')?'':$m.'.php'.'/';
	return base_url().$m;
}

function rand_pass($length)
{
	$pool = '0123456789abcdefghijklmnopqrstuvwxyz';

	$str = '';
	for ($i = 0; $i < $length; $i++)
	{
		$str .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
	}
	return $str;
}

function create_id($string, $length=5, $prefix='')
{
	$id=$prefix;
	if($string=="")
	{
		for($i=0; $i<($length-1); $i++)
			$id.='0';
		$id.='1';
	}
	else
	{
		$temp=((int)substr($string,(abs(strlen($string)-$length)),strlen($string))+1);
		$n=$length-strlen($temp);
		$str='';
		for($i=0;$i<$n;$i++)
		{
			$str.='0';
		} 
		$id.=$str.$temp;
	}
	return $id;
}

function error_form($field)
{
	$admin= new CI_Admin();
    $error = $admin->GetFlashData('error_form');
    if(isset($error[$field]))
        return $error[$field];
	return '';
}

function msg_form($field,$color = 'red')
{
	$admin= new CI_Admin();
    $msg = $admin->GetFlashData('msg_form');
    if(isset($msg[$field]))
        return '<font color="'.$color.'">'.$msg[$field].'</font>';
	return '';
}

function url_tmpl()
{
	$admin = new CI_Admin();
	return base_url().$admin->path;
}